package com.ice.body.business.controller;

import cn.hutool.json.JSONUtil;
import com.google.gson.JsonObject;
import com.ice.base.model.SysLoginModel;
import com.ice.base.result.AjaxResult;
import com.ice.base.result.ResponseResult;
import com.ice.base.util.HexUtil;
import com.ice.base.util.IOUtil;
import com.ice.base.util.RedisUtil;
import com.ice.base.util.VoiceUtil;
import com.ice.body.business.model.ReagentOwn;
import com.ice.body.business.model.ReagentStock;
import com.ice.body.business.service.ReagentOwnService;
import com.ice.body.business.service.ReagentStockService;
import com.ice.body.client.FaceLogModel;
import com.ice.body.hardware.model.DeviceIo;
import com.ice.body.hardware.service.DeviceIoService;
import com.ice.body.hardware.service.DeviceVideoService;
import com.ice.body.hardware.service.FaceToRoomService;
import com.ice.body.log.model.LogAir;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Api(tags = "各种测试接口")
@RestController
public class ATestApi {

    @Resource
    private VoiceUtil voiceUtil;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private IOUtil ioUtil;
    @Resource
    private DeviceVideoService deviceVideoService;
    @Resource
    private DeviceIoService deviceIoService;
    @Resource
    private ReagentStockService reagentStockService;
    @Resource
    private ReagentOwnService reagentOwnService;


    //翻转屏
    @Value("${flipScree.ip}")
    private String flipIp;

    @Value("${flipScree.port}")
    private String flipPort;

    @Value("${flipScree.open}")
    private String open;

    @Value("${flipScree.close}")
    private String close;


    @ApiOperation(value = "脚本修改数据")
    @RequestMapping("/testData")
    public void testData() {
        ReagentOwn own ;
        ArrayList<ReagentStock> reagentStocks = reagentStockService.selectAll();
        try{
            for (ReagentStock r:reagentStocks) {

                own = reagentOwnService.getByCname(r.getCName());
                if(null != own){
                    own.setTotalCount(own.getTotalCount()+1);
                    reagentOwnService.update(own);
                }else{
                    own = new ReagentOwn();
                    own.setCName(r.getCName());
                    own.setTotalCount(1);
                    own.setCasNo(r.getCasNo());
                    own.setLower(0);
                    own.setSpecification(r.getSpecification());

                    own.setCreateTime(new Date());
                    reagentOwnService.insert(own);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }



    }




    @ApiOperation(value = "测试语音")
    @RequestMapping("/testVoice")
    public void testVoice() {
        voiceUtil.sendVoice("192.168.90.19","50002","测试");
    }


    @ApiOperation(value = "测试翻转屏开")
    @RequestMapping("/testOpenFlip")
    public void testOpenFlip() {
        ioUtil.operIo(flipIp,flipPort,open);
    }

    @ApiOperation(value = "测试翻转屏关")
    @RequestMapping("/testCloseFlip")
    public void testCloseFlip() {
        ioUtil.operIo(flipIp,flipPort,close);
    }


    @ApiOperation(value = "海康视频 - 开")
    @RequestMapping("/openVideo")
    public void openVideo(){
        try{
            deviceVideoService.makeVideo("1");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @ApiOperation(value = "海康视频 - 关")
    @RequestMapping("/closeVideo")
    public void closeVideo(){
        try{
            deviceVideoService.logout("1");
        }catch (Exception e){
            e.printStackTrace();
        }
    }



    @Resource
    private RestTemplate restTemplate;

    @ApiOperation(value = "测试刷脸数据上传")
    @PostMapping("/faceLog/insert")
    public AjaxResult<T> testFaceLog() {
        AjaxResult r = ResponseResult.success();
        FaceLogModel model = new FaceLogModel();

        model.setFaceType("1");
        model.setUserName("张三");
        model.setSerialNo("19543867");
        model.setUserNo("19543867");

        String json = JSONUtil.toJsonStr(model);
        HttpHeaders headers =  new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(json,headers);
        try{
            String stringResponseEntity = restTemplate.postForObject("http://192.168.100.110:8085/rpcLab/faceLog/insert", entity, String.class);
//            HttpStatus statusCode = stringResponseEntity.getStatusCode();
//            System.out.println("发送成功,返回状态码：" + statusCode.toString()+statusCode.value());
            System.out.println(stringResponseEntity);
        }catch (Exception e){
            e.printStackTrace();
        }

        return r;
    }






    @ApiOperation(value = "空气质量测试")
    @RequestMapping("/showMonitor")
    public Map<String, Object> showMonitor() throws IOException {
        Map<String, Object> resultMap = new HashMap<>();
        Socket socket = null;
        try {
            System.out.println("空气质量检测开始~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
            // 连接空气质量检测设备
            socket = new Socket(InetAddress.getByName("192.168.90.17"), Integer.parseInt("8234"));
            socket.setSoTimeout(5000);
            // 得到Socket连接的输出流
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());
            // 向服务器发送数据  1A190501028686860F   1A210502098686860F  1A210701018686860F
            out.write(HexUtil.hex2Bytes("1A210701048686860F"));
            // 立刻发送数据
            out.flush();
            //socket.shutdownOutput();
            DataInputStream in = new DataInputStream(socket.getInputStream());
            byte[] bytes = new byte[32];
            for (byte b:bytes) {
                System.out.print(b);
            }
            int size = in.read(bytes);
            String dataStr = "";
            if (size > 0) {
                dataStr = HexUtil.bytes2Hex(bytes).substring(0, 54);
            }
            socket.close();
            System.out.println(dataStr);
            if (!StringUtils.isEmpty(dataStr)) {
                int formaldehyde = Integer.parseInt(dataStr.substring(10, 14), 16);
                int tvoc = Integer.parseInt(dataStr.substring(16, 20), 16);
                int pm = Integer.parseInt(dataStr.substring(22, 26), 16);
                int temperature = Integer.parseInt(dataStr.substring(28, 32), 16);
                int humidity = Integer.parseInt(dataStr.substring(34, 38), 16);
                int airQuality = Integer.parseInt(dataStr.substring(40, 44), 16);
                int carbonDioxide = Integer.parseInt(dataStr.substring(46, 50), 16);
                log.info("甲醛浓度：" + formaldehyde +",TVOC浓度：" + tvoc + ",PM2.5浓度：" +  pm
                        + ",温度：" + temperature + "湿度：" + humidity + "%," +
                        "空气质量指标：" + airQuality + "二氧化碳：" + carbonDioxide
                );
            }

        } catch (Exception e) {
            e.printStackTrace();
            socket.close();
        }
        return resultMap;
    }


    @ApiOperation(value = "测试加一个用户")
    @RequestMapping("/addUser")
    public void addUser() throws Exception{
        ArrayList userList = new ArrayList();
        SysLoginModel user = new SysLoginModel();
        user.setUserName("李逵");
        user.setRealName("张飞");
        userList.add(user);
        redisUtil.set("1userList",userList);
    }

   /* @ApiOperation(value = "测试加一个试剂")
    @RequestMapping("/addReagent")
    public void addReagent() throws Exception{
        String epcCode = "";
        ReagentStock stockModel = reagentStockService.getByEpcCode(epcCode);
        if(null == stockModel){
            log.error("不存在的标签：" + epcCode);
            return;
        }else if (stockModel.getState().equals("0")) {
            List<ReagentStock> rkList = redisUtil.get(1 + "rkList") == null ? new ArrayList<>() : (ArrayList) redisUtil.get(1 + "rkList");   //入库
            for (ReagentStock rkModel : rkList) {
                if (rkModel.getEpcCode().equals(epcCode)) {
                    log.error("入库重复扫描标签：" + epcCode);
                    return;
                }
            }

            stockModel.setState("1");//在库
            rkList.add(stockModel);
            redisUtil.set(1 + "rkList", rkList);
        }


    }
*/


    @ApiOperation(value = "测试io 出门 关全币")
    @RequestMapping("/io")
    public void testIo() throws Exception{
        log.info("出门结算关闭硬件");
        DeviceIo ioModel = new DeviceIo();
        ioModel.setWarehouseId("1");
        ioModel.setSwitchType(2);

        ArrayList<DeviceIo> list = deviceIoService.selectListByModel(ioModel);
        String doorIp =list.get(0).getIp().trim();
        String doorPort=list.get(0).getPort().trim();
        String command = list.get(0).getCommand().trim();

        // 开启IO模块1命令  开门
        ioUtil.operIo(doorIp,doorPort,"CCDDA10100010001A448");
        //翻转屏
        ioUtil.operIo(flipIp,flipPort,close);
        //延迟10s秒关门
        TimeUnit.SECONDS.sleep(10);
        log.info("结算出门 关门命令 ："+ command);
        ioUtil.operIo(doorIp,doorPort,command);

        ioUtil.operIo("192.168.90.18","50000","CCDDA10100010001A448");
        TimeUnit.SECONDS.sleep(10);
        ioUtil.operIo("192.168.90.18","50000","CCDDA1010000FFFFA040");
    }
}
